package com.monster.servlet.player;

import com.alibaba.fastjson.JSON;
import com.monster.pojo.Lyric;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;

@WebServlet("/music/lyric")
public class LyricServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList<Lyric> lyrics = new ArrayList<>();
        String lyricJSON = null;
        String path = this.getServletContext().getRealPath(request.getParameter("url"));
        InputStreamReader isr = new InputStreamReader(new FileInputStream(path), "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String str = null;
        String[] strs = null;
        String time = null;
        String lyr = null;
        while ((str = br.readLine()) != null) {
            if (str.charAt(1) < 48 || str.charAt(1) > 57) {
                continue;
            }
            strs = str.split("]");
            time = strs[0].substring(1);
            if (strs.length == 1) {
                lyr = "&nbsp;";
            } else {
                lyr = strs[1];
            }
            Lyric lyric = new Lyric(time, lyr);
            lyrics.add(lyric);
        }
        lyricJSON = JSON.toJSONString(lyrics);
        PrintWriter out = response.getWriter();
        out.print(lyricJSON);
        out.flush();
        out.close();
        br.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
